package com.atguigu.tingshu.user.service.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.*;
import com.atguigu.tingshu.user.factory.PurchaseStrategyFactory;
import com.atguigu.tingshu.user.mapper.*;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.strategy.PurchaseStrategy;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @Autowired
    private PurchaseStrategyFactory purchaseStrategyFactory;

    @Override
    public void updateVipExpireStatus() {
        //  先查询哪些vip 用户已过期.
        //  update user_info set is_vip = 0 where is_vip = 1 and vip_expire_time < now();
        //  创建更新对象
        UserInfo userInfo = new UserInfo();
        userInfo.setIsVip(0);
        //  创建更新条件
        LambdaUpdateWrapper<UserInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserInfo::getIsVip,1).lt(UserInfo::getVipExpireTime,new Date());
        userInfoMapper.update(userInfo,wrapper);

        //  第二种： 先查询 is_vip = 1 and vip_expire_time < now() 再 更新is_vip=0;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserPaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //  获取工厂对象
        PurchaseStrategy strategy = purchaseStrategyFactory.getStrategy(userPaidRecordVo.getItemType());
        //  判断
        if (null!=strategy){
            strategy.purchase(userPaidRecordVo);
        }

        //	判断用户购买的类型，记录信息.
        //	标识购买专辑记录在用户购买专辑表user_paid_album
        //        if (userPaidRecordVo.getItemType().equals(SystemConstant.ORDER_ITEM_TYPE_ALBUM)) {
        //            //	判断当前用户是否已经记录了购买专辑信息.
        //            UserPaidAlbum userPaidAlbum = this.userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getAlbumId, userPaidRecordVo.getItemIdList().get(0)).eq(UserPaidAlbum::getUserId, userPaidRecordVo.getUserId()));
        //            //	判断
        //            if (null != userPaidAlbum) {
        //                //	说明已经记录过。
        //                log.info("当前用户{} 已购买过专辑Id{}", userPaidRecordVo.getUserId(), userPaidRecordVo.getItemIdList().get(0));
        //                return;
        //            }
        //            //	记录信息.
        //            userPaidAlbum = new UserPaidAlbum();
        //            //	赋值
        //            userPaidAlbum.setUserId(userPaidRecordVo.getUserId());
        //            userPaidAlbum.setOrderNo(userPaidRecordVo.getOrderNo());
        //            userPaidAlbum.setAlbumId(userPaidRecordVo.getItemIdList().get(0));
        //            this.userPaidAlbumMapper.insert(userPaidAlbum);
        //
        //        } else if (userPaidRecordVo.getItemType().equals(SystemConstant.ORDER_ITEM_TYPE_TRACK)) {
        //            //	购买声音. user_paid_track
        //            LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<>();
        //            wrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
        //            Long count = userPaidTrackMapper.selectCount(wrapper);
        //            if (count > 0) {
        //                //  记录日志
        //                log.info("当前用户{} 已购买过声音Id,对应的订单编号{}", userPaidRecordVo.getUserId(), userPaidRecordVo.getOrderNo());
        //                return;
        //            }
        //            //  获取专辑Id,声音对象中有专辑Id.
        //            Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0));
        //            Assert.notNull(trackInfoResult, "返回声音结果集为空");
        //            TrackInfo trackInfo = trackInfoResult.getData();
        //            Assert.notNull(trackInfo, "声音对象为空");
        //            //  存储数据. 循环遍历
        //            for (Long trackId : userPaidRecordVo.getItemIdList()) {
        //                UserPaidTrack userPaidTrack = new UserPaidTrack();
        //                //  赋值：
        //                userPaidTrack.setUserId(userPaidRecordVo.getUserId());
        //                userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
        //                userPaidTrack.setAlbumId(trackInfo.getAlbumId());
        //                userPaidTrack.setTrackId(trackId);
        //                this.userPaidTrackMapper.insert(userPaidTrack);
        //            }
        //        } else {
        //            //	购买vip user_vip_service ，不需要去重注意订单No-校验；因为vip 可以续期.
        //            Long count = this.userVipServiceMapper.selectCount(new LambdaQueryWrapper<UserVipService>().eq(UserVipService::getOrderNo, userPaidRecordVo.getOrderNo()));
        //            if (count>0){
        //                return;
        //            }
        //            //  1.保存记录 user_vip_service 2.更新 user_info.is_vip=1, user_info.vip_expire_time
        //
        //            //  获取用户购买vip信息对象.
        //            Long vipServiceConfigId = userPaidRecordVo.getItemIdList().get(0);
        //            VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(vipServiceConfigId);
        //            //  购买的时长.
        //            Integer serviceMonth = vipServiceConfig.getServiceMonth();
        //            //  获取到用户基本信息.
        //            UserInfo userinfo = this.getById(userPaidRecordVo.getUserId());
        //
        //            //  创建对象
        //            UserVipService userVipService = new UserVipService();
        //            userVipService.setUserId(userPaidRecordVo.getUserId());
        //            userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        //            //  当前创建时间.
        //            userVipService.setStartTime(new Date());
        //            //  当前系统时间
        //            Date currentTime = new Date();
        //            //  判断 续期
        //            if (userinfo.getIsVip() == 1 && userinfo.getVipExpireTime().after(new Date())) {
        //                //  月份累加：
        //                currentTime = new LocalDateTime(userinfo.getVipExpireTime()).toDate();
        //            }
        //            //  月份相加：
        //            LocalDateTime localDateTime = new LocalDateTime(currentTime).plusMonths(serviceMonth);
        //            userVipService.setExpireTime(localDateTime.toDate());
        //            //  保存
        //            userVipServiceMapper.insert(userVipService);
        //            //  int i = 1/0;
        //            //  赋值：
        //            userinfo.setIsVip(1);
        //            userinfo.setVipExpireTime(localDateTime.toDate());
        //            this.updateById(userinfo);
        //        }
    }

    /**
     * 根据专辑id获取用户支付过的声音id列表
     *
     * @param userId
     * @param albumId
     * @return
     */
    @Override
    public List<Long> findUserPaidTrackList(Long userId, Long albumId) {
        // select * from user_paid_track where user_id = ? and album_id = ?;
        return userPaidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getAlbumId, albumId).eq(UserPaidTrack::getUserId, userId)).stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
    }

    @Override
    public Boolean isPaidAlbum(Long userId, Long albumId) {
        //	select * from user_paid_album where user_id = ? and album_id = ?;
        //	zookeeper-client;
        return userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getAlbumId, albumId).eq(UserPaidAlbum::getUserId, userId)) != null;
    }

    @Override
    public Map<Long, Integer> userIsPaidTrack(Long albumId, Long userId, List<Long> trackIdList) {
        //	声明集合
        Map<Long, Integer> map = new HashMap<>();
        //	key=trackId value = 1或0; 1:表示购买过，0：表示没有购买过
        //	判断当前这个用户是否购买过专辑. user_paid_album
        //	select album_id from user_paid_album where user_id = ? and album_id = ?;
        UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getAlbumId, albumId).eq(UserPaidAlbum::getUserId, userId));
        //	判断这个对象是否为空
        if (null != userPaidAlbum) {
            //	购买过专辑，专辑对应的声音列表都是免费的。
            for (Long trackId : trackIdList) {
                //	不需要付费
                map.put(trackId, 1);
            }
            //	Map<Long, Integer> integerMap = trackIdList.stream().collect(Collectors.toMap(trackId -> trackId, trackId -> 1));
            return map;
        } else {
            //	当前这个用户可能购买过声音. user_paid_track
            //  select * from user_paid_track where user_id = ? and track_id in ?;
            LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserPaidTrack::getUserId, userId).in(UserPaidTrack::getTrackId, trackIdList);
            //	当前用户可能购买的声音列表集合
            List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(wrapper);
            //	付费的声音Id集合列表
            List<Long> userPaidTrackIdList = userPaidTrackList.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
            //	循环遍历要购买的声音列表.
            for (Long trackId : trackIdList) {
                //	判断
                if (!CollectionUtils.isEmpty(userPaidTrackList)) {
                    //	判断是否包含.
                    if (userPaidTrackIdList.contains(trackId)) {
                        //	购买过声音
                        map.put(trackId, 1);
                    } else {
                        //	没有购买过声音
                        map.put(trackId, 0);
                    }
                } else {
                    //  默认初始值为0
                    map.put(trackId, 0);
                }
            }
            //	返回数据
            return map;
        }
    }

    @Override
    public UserInfoVo getUserInfo(Long userId) {
        //	调用方法获取对象
        UserInfo userInfo = this.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        //	返回数据
        return userInfoVo;
    }

    @Override
    public void updateUser(Long userId, UserInfoVo userInfoVo) {
        //	创建对象
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoVo, userInfo);
        userInfo.setId(userId);
        //	修改数据
        userInfoMapper.updateById(userInfo);
    }
}
